import { O2mBase } from './o2mbase.js'

export class O2mForm extends O2mBase {
  constructor(payload = {}) {
    super(payload)
  }

  get rules() {
    return this.node.rules
  }

  new_editmodel() {
    // call by o2m formview page, click editable button
    return this.relation_node.relation.Editmodel
  }

  // todo 该函数改为 内部函数.
  get_fields_all(kwargs = {}) {
    const fs = this.fields

    const { editmodel } = kwargs
    if (editmodel) {
      return editmodel.get_fields_all(fs)
    } else {
      return this.Model.get_fields_all(fs)
    }
  }

  _get_arch_sheet(kwargs = {}) {
    const { arch } = this.config
    const { sheet } = arch
    const self = this

    function prepare_data() {
      const { parent_info } = kwargs
      const { record: record0, values: values0, editable: editable0 } = kwargs

      const Editmodel = self.env.editx2m(self.model, {
        field_info: self.node.meta
      })

      const record_without_prt = Editmodel._merge_to_modifiers(record0, values0)
      const record_onchange_without_prt = Editmodel._merge_to_onchange(
        record0,
        values0
      )

      const parent_data = self.get_parent_data(parent_info)

      const record = { ...record_without_prt, parent: parent_data }
      const record_onchange = {
        ...record_onchange_without_prt,
        parent: parent_data
      }

      const editable = editable0 && !self.node.readonly

      return { editable, record, record_onchange }
    }

    const datas = prepare_data()

    const for_view = 'o2m.form'
    const kws = { for_view, ...datas }
    // console.log(kws)
    return this.get_arch_for_node(sheet, kws)
  }

  _get_sheet(kwargs = {}) {
    if (this.check_has_sheet()) {
      return this._get_arch_sheet(kwargs)
    } else {
      const fs = this.get_fields_all(kwargs)

      return Object.keys(fs).reduce((acc, fld) => {
        acc[fld] = {
          ...fs[fld],
          tagname: 'odoofield',
          string: fs[fld].meta.string
        }
        return acc
      }, {})
    }
  }

  get_sheet(kwargs = {}) {
    const children = this._get_sheet(kwargs)
    return {
      children,
      nodename: 'sheet',
      tagname: 'sheet'
    }
  }
}
